import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class SendService implements Runnable {
	
	//ATTRIBUTI CLASSE 
		private DatagramSocket sendingSocket;
		private InetAddress IPTC;
        private int portChannel = 65432;
		private Cell[] cella;
		private int N;
		private boolean safeExit;
	
	//METODO COSTRUTTORE
		public SendService(InetAddress IPTCh, Cell[] cella, DatagramSocket sendingSocket, int N, int L) throws SocketException, UnknownHostException {
			this.sendingSocket = sendingSocket;
			this.IPTC = IPTCh;
			this.cella = cella;
			this.N = N;
			this.safeExit = false;//1 + (int)(Math.log(0.80/Math.exp(-L/1024))/(Math.log(1-Math.exp(-L/1024))));
		
		}
		
		public boolean isSafe() {
			return safeExit;
		}
		
		public void run() {
			System.out.println("SendServicee running...");
			int indexM = 0;
			try {
				
				int cont = 0;
				
				// Server is waiting
				while(cont != N-1) {
					cont = 0;
					for (int i=0; i<this.cella.length; i++){
					if	(this.cella[i] != null)	
						if (this.cella[i].getTime() == 0) {
								indexM = i;
								DatagramPacket sendPacket = new DatagramPacket(this.cella[i].getPacket().toByte(), this.cella[i].getPacket().toByte().length, this.IPTC , this.portChannel);
								this.sendingSocket.send(sendPacket);
						}else cont++;
					}
				}
			}catch(IOException e) {
						e.printStackTrace();
			}
		
			System.out.println("Mando ultimo:"+ indexM+ " SAFE EXIT");
			Packet lastPacket = new Packet(cella[indexM].getPacket().getIPDestination(), cella[indexM].getPacket().getPortDestination(), cella[indexM].getPacket().getIPSource(), cella[indexM].getPacket().getPortSource(), 65535, cella[indexM].getPacket().getData());
			DatagramPacket sendPacket = new DatagramPacket(lastPacket.toByte(), lastPacket.toByte().length, this.IPTC , this.portChannel);
			boolean response = false;
			while (!response) {
				try {
					this.sendingSocket.send(sendPacket);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				if (cella[indexM].getTime() == 1){
					response = true;
					
					}
				
			}
		
			this.safeExit = true;	
			
		}		
}
	
